package com.zhangjianbing.hystrix.custom02.annotation;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangjianbing
 * time 2021/2/20
 */
@Slf4j
@Aspect
@Component
public class HystixAspect {

    /**
     * key: 服务的id
     * value：该服务对应的拦截器
     */
    private Map<String, HystixCmd> hystixCmds = new HashMap<>();

    {
        // 注入此服务的拦截器
        hystixCmds.put("application-name", new HystixCmdImpl());
    }

    @Around("@annotation(com.zhangjianbing.hystrix.custom02.annotation.HystixCmdRpc)")
    public Object interceptor(ProceedingJoinPoint point) {
        // 从容器里面取自己的拦截器
        HystixCmd hystixCmd = hystixCmds.get("application-name");
        switch (hystixCmd.getStatus()) {
            case OPEN:
                return hystixCmd.interceptor(point);
            case CLOSE:
                return hystixCmd.pass(point);
            case HALF_OPEN:
                log.info("测试一下提供服务的接口是否连通");
                return hystixCmd.test(point);
            default:
                break;
        }
        // 没有符合的条件
        return null;
    }

}
